//
//  MDHCommonTableViewCell.swift
//  JSTech
//
//  Created by 高得华 on 2019/5/9.
//  Copyright © 2020 华&梅. All rights reserved.
//

import UIKit


class MDHCommonTableViewCell: MDHTableViewCell {

    //MARK: - ==== 属性
    ///viewModel
    @objc dynamic var viewModel = MDHCommonItemViewModel()
    ///箭头
    @objc lazy var rightArrow: UIImageView = {
        let imv = SDAnimatedImageView(image: UIImage(named: "jiantou_right_hs")?.byTintColor(kColor_MDHHex("#7362AC")))
        return imv
    }()
    /// 开关
    @objc lazy var rightSwitch: UISwitch = {
        let sw = UISwitch()
        sw.onImage = UIImage(named: "chat_room_kaiguan")
        sw.offImage = UIImage(named: "chat_room_guanbi")
        sw.rac_signal(for: UIControl.Event.valueChanged)
            .deliverOnMainThread().subscribeNext({ [weak self] (x) in
            if let weakSelf = self {
                let switchViewModel = weakSelf.viewModel as! MDHCommonSwitchItemViewModel
                switchViewModel.off = !((x as! UISwitch).isOn)
            }
        })
        return sw
    }()
    ///button-switch
    lazy var button_switch: MDHButton = {
        let btn = MDHButton()
        let scale = kMDHPTAutoScale()
        btn.frame = CGRect(x: 0, y: 0, width: 40*scale, height: 24*scale)
        btn.setBackgroundImage(UIImage(named: "chat_room_kaiguan"), for: .selected)
        btn.setBackgroundImage(UIImage(named: "chat_room_guanbi"), for: .normal)
        btn.rac_signal(for: UIControl.Event.touchUpInside)
            .deliverOnMainThread().subscribeNext({ [weak self] (x) in
            if let weakSelf = self {
                let switchViewModel = weakSelf.viewModel as! MDHCommonSwitchItemViewModel
                switchViewModel.off = !switchViewModel.off//!((x as? MDHButton)?.isSelected ?? false)
                if let block = weakSelf.viewModel.blockBackData {
                    block(weakSelf.viewModel)
                }
            }
        })
        return btn
    }()
    
    /// 标签
    @objc lazy var rightLabel: UILabel = {
        let label = UILabel()
        label.isHidden = true
        label.textAlignment = .right
        label.sizeToFit()
        return label
    }()
    /// avatar 头像
    @objc lazy var avatarView: UIImageView = {
        let imv = SDAnimatedImageView()
        imv.isHidden = true
        return imv
    }()
    /// QrCode
    @objc lazy var qrCodeView: UIImageView = {
        let imv = SDAnimatedImageView()
        imv.isHidden = true
        return imv
    }()
    /// 三条分割线
    @objc lazy var divider0: UIImageView = {
        return self.createDividerLine()
    }()
    @objc lazy var divider1: UIImageView = {
        return self.createDividerLine()
    }()
    @objc lazy var divider2: UIImageView = {
        return self.createDividerLine()
    }()
    ///创建分界线
    fileprivate func createDividerLine() -> UIImageView {
        let imv = MDHSwiftHeader.createUnifiedViewLine()
        imv.isHidden = true
        imv.backgroundColor = kColor_MDHEEEEEE()
        return imv
    }
    /// 中间偏左 view
    @objc lazy var centerLeftView: UIImageView = {
        let imv = SDAnimatedImageView()
        imv.isHidden = true
        return imv
    }()
    /// 中间偏右 view
    @objc lazy var centerRightView: UIImageView = {
        let imv = SDAnimatedImageView()
        imv.isHidden = true
        return imv
    }()
    
    required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        ///设置视图
        self.setup()
        ///设置自定义视图
        self.setupSubViews()
        ///设置布局
        self.makeSubViewsConstraints()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 初始化
    fileprivate func setup() -> () {
        self.backgroundColor = kColor_MDHFFFFFF()
        self.contentView.backgroundColor = kColor_MDHFFFFFF()
        self.textLabel?.textColor = kColor_MDH333333()//init(hexString: "#888888")
        self.detailTextLabel?.textColor = kColor_MDH767676()//init(hexString: "#888888")
        self.detailTextLabel?.numberOfLines = 0
        self.textLabel?.font = UIFont.systemFont(ofSize: 15)
        self.detailTextLabel?.font = UIFont.systemFont(ofSize: 11)
    }
    //MARK: - 创建自控制器
    fileprivate func setupSubViews() -> () {
        /// CoderMikeHe Fixed : 这里需要把divider添加到self，而不是self.contentView ,由于添加了 accessView，导致self.contentView的宽度<self的宽度
        ///分割线
        self.contentView.addSubview(self.divider0)
        self.contentView.addSubview(self.divider1)
        self.contentView.addSubview(self.divider2)
        
        /// 添加用户头像
        self.contentView.addSubview(self.avatarView)
        /// 二维码照片
        self.contentView.addSubview(self.qrCodeView)
        /// 中间偏左的图片
        self.contentView.addSubview(self.centerLeftView)
        /// 中间偏右 view
        self.contentView.addSubview(self.centerRightView)
        ///设置标签Label
        self.contentView.addSubview(self.rightLabel)
        
        ///设置数据
        self.rac_values(forKeyPath: "viewModel.badgeValue", observer: self).deliverOnMainThread().subscribeNext({ [weak self] (x) in
            if let weakSelf = self {
                let att = x as? NSAttributedString ?? NSAttributedString()
                if att.string.count > 0 {
                    weakSelf.rightLabel.attributedText = att
                }
            }
        })
    }
    //MARK:  - 布局子控件
    fileprivate func makeSubViewsConstraints() -> () {
        
    }
    //MARK:  - 布局
    override func layoutSubviews() {
        super.layoutSubviews()
        /// 设置
        let pathTd = (self.textLabel?.mj_x ?? 2) - (self.detailTextLabel?.mj_x ?? 0)
        if pathTd <= -0.1 || self.viewModel.subtitle.count > 0 {
            /// SubTitle
            self.textLabel?.mh_bottom = (self.detailTextLabel?.mh_top ?? 0)//-1
        }else{
            self.textLabel?.mh_centerY = self.mh_height*0.5
        }
        
        ///设置分界线
        self.divider0.frame = CGRect.init(x: 0, y: 0, width: self.mh_width, height: MHGlobalBottomLineHeight)
        self.divider1.frame = CGRect.init(x: 14, y: self.mh_height-MHGlobalBottomLineHeight, width: self.mh_width-14, height: MHGlobalBottomLineHeight)
        self.divider2.frame = CGRect.init(x: 0, y: self.mh_height-MHGlobalBottomLineHeight, width: self.mh_width, height: MHGlobalBottomLineHeight)
        
        ///设置头像
        self.avatarView.mh_size = CGSize.init(width: 66, height: 66)
        self.avatarView.mh_right = (self.accessoryView?.mh_left ?? 0)-7
        self.avatarView.mh_centerY = self.mh_height*0.5
        
        /// 设置二维码
        self.qrCodeView.mh_right = (self.accessoryView?.mh_left ?? 0) - 11;
        self.qrCodeView.mh_centerY = self.mh_height*0.5
        
        /// 配置Artboard
        self.centerLeftView.mh_left = (self.textLabel?.mh_right ?? 0) + 14;
        self.centerLeftView.mh_centerY = self.mh_height*0.5
        
        /// 配置
        self.centerRightView.mh_right = (self.detailTextLabel?.mh_left ?? 0) - 5;
        self.centerRightView.mh_centerY = self.mh_height*0.5
        
        ///右边的标签 Label
        self.rightLabel.mas_makeConstraints { (make) in
            make?.centerY.equalTo()(0)
            make?.height.equalTo()(20)
            if self.accessoryView != nil {
                make?.right.equalTo()(self.accessoryView?.mas_left)?.offset()(-5)
            }else{
                make?.right.equalTo()(-12)
            }
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    ///设置数据
    override func bindViewModel(_ viewModel: Any!) {
        let m = viewModel as? MDHCommonItemViewModel ?? MDHCommonItemViewModel()
        self.viewModel = m
        
        self.avatarView.isHidden = true
        self.qrCodeView.isHidden = true
        
        ///原有的
        self.selectionStyle = m.selectionStyle
        self.textLabel?.text = m.title
        if m.icon.count > 0 {
            self.imageView?.image = UIImage.init(named: m.icon)
        }
        self.detailTextLabel?.text = m.subtitle
        
        /// 设置全新
        if m.centerLeftViewName.count > 0 {
            self.centerLeftView.isHidden = false
            self.centerLeftView.image = UIImage.init(named: m.centerLeftViewName)
            self.centerLeftView.mh_size = self.centerLeftView.image?.size ?? CGSize.zero
        }else{
            self.centerLeftView.isHidden = true
        }
        
        /// 设置锁
        if m.centerRightViewName.count > 0 {
            self.centerRightView.isHidden = false
            self.centerRightView.image = UIImage.init(named: m.centerRightViewName)
            self.centerRightView.mh_size = self.centerRightView.image?.size ?? CGSize.zero
        }else{
            self.centerRightView.isHidden = true
        }
        
        /// 纯带箭头
        if m.isMember(of: MDHCommonArrowItemViewModel.classForCoder()) {
            self.accessoryView = self.rightArrow
            if m.isMember(of: MDHCommonAvatarItemViewModel.classForCoder()) { // 头像
                let avatarViewModel = viewModel as! MDHCommonAvatarItemViewModel
                self.avatarView.isHidden = false
                self.avatarView.sd_setImage(with: URL.init(string: avatarViewModel.avatar)!, placeholderImage: MDHWebImagePlaceholder())
            }else if m.isMember(of: MDHCommonQRCodeItemViewModel.classForCoder()) { // 二维码
                self.qrCodeView.isHidden = false
            }
        }else if m.isMember(of: MDHCommonSwitchItemViewModel.classForCoder()) { /// 开关
            // 右边显示开关
            let switchViewModel = viewModel as! MDHCommonSwitchItemViewModel
            //self.accessoryView = self.rightSwitch
            //self.rightSwitch.isOn = !switchViewModel.off
            self.accessoryView = self.button_switch
            self.button_switch.isSelected = !switchViewModel.off
        }else{
            self.accessoryView = nil
        }

        ///右边的标签
        if m.badgeValue.string.count > 0 {
            self.rightLabel.isHidden = false
        }else{
            self.rightLabel.isHidden = true
        }
    }
    
    override func setIndexPath(indexPath: IndexPath, rowsInSection rows: Int) {
        self.divider1.isHidden = indexPath.row == rows-1
        /*self.divider0.isHidden = false
        self.divider1.isHidden = false
        self.divider2.isHidden = false
        if rows == 1 {/// 一段
            self.divider1.isHidden = true
        }else if indexPath.row == 0 { /// 首行
            self.divider2.isHidden = true
            self.divider0.isHidden = true
        }else if indexPath.row == rows-1 { /// 末行
            self.divider0.isHidden = true
            self.divider1.isHidden = true
        }else{
            self.divider0.isHidden = true
            //self.divider1.isHidden = false
            self.divider2.isHidden = true
        }*/
    }
}
